package com.briup.estore.service;

import com.briup.estore.bean.User;
import com.briup.estore.constant.BookStoreConstant;
import com.briup.estore.dto.UserLoginDTO;
import com.briup.estore.dto.UserRegisterDTO;
import com.briup.estore.exception.BookStoreException;
import com.briup.estore.mapper.UserMapper;
import com.briup.estore.utils.BeanCopyUtils;
import com.briup.estore.utils.JsonWebTokenUtils;
import com.briup.estore.vo.UserInfoVO;
import com.briup.estore.vo.UserLoginVO;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Objects;

@Service
public class UserService {
    @Resource
    private UserMapper userMapper;

    public UserLoginVO login(UserLoginDTO userLoginDTO, Integer roleId) {
//判断用户名是否为空
        if (!StringUtils.hasText(userLoginDTO.getUsername())) {
            throw new
                    BookStoreException(BookStoreException.CodeMsgEnum.USER_USERNAME_IS_NOT_NULL);
        }
//判断密码是否为空
        if (!StringUtils.hasText(userLoginDTO.getPassword())) {
            throw new
                    BookStoreException(BookStoreException.CodeMsgEnum.USER_PASSWORD_IS_NOT_NULL);
        }
//判断用户名密码是否正确
        User user =
                userMapper.getUserByUsernameAndPassword(userLoginDTO.getUsername(),userLoginDTO.getPassword());
        if (Objects.isNull(user)) {
            throw new BookStoreException(BookStoreException.CodeMsgEnum.USER_USERNAME_OR_PASSWORD_ERROR);
        }
//用户名和密码均正确
//验证账号状态是否为正常状态
        if (user.getStatus().intValue() == BookStoreConstant.LOGIN_STATUS_CLOSE) {
            throw new
                    BookStoreException(BookStoreException.CodeMsgEnum.USER_STATUS_CLOSE);
        }
//验证是否为管理员身份
        if (user.getRoleId().intValue() != roleId) {
//非管理员
            throw new
                    BookStoreException(BookStoreException.CodeMsgEnum.LOGIN_IDENTITY_IS_INVALID);
        }
//登录者为管理员，根据管理员ID生成JWT
        String jwt = JsonWebTokenUtils.createJWT(user.getId().toString());
//Bean拷贝
        UserInfoVO userInfo = BeanCopyUtils.copyBean(user, UserInfoVO.class);
//创建VO对象
        UserLoginVO userLoginVO = new UserLoginVO();
//封装jwt、用户信息在VO对象中
        userLoginVO.setJwt(jwt);
        userLoginVO.setUserInfo(userInfo);
//返回统一响应
        return userLoginVO;
    }

    public UserInfoVO getUserInfo(String id) {
//根据用户ID查询用户信息
        User user = userMapper.getUserById(Integer.parseInt(id));
//bean拷贝
        UserInfoVO userInfoVO = BeanCopyUtils.copyBean(user, UserInfoVO.class);
        return userInfoVO;
    }

    public void register(UserRegisterDTO userRegisterDTO) {
        userMapper.register(userRegisterDTO);
//        return  user;
    }
}
